package com.totcy.atom.model;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.totcy.atom.CommonValues;
import com.totcy.atom.bean.ImagesBean;
import com.totcy.atom.presenter.contract.ImageListContract;
import com.totcy.baselibrary.base.mvpbase.BaseModelImpl;
import com.totcy.baselibrary.httpcache.ACache;
import com.totcy.baselibrary.utils.NetUtil;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

import static com.totcy.atom.view.activity.ImageListActivity.PAGE_START;

/**
 * description: xxxiao 分类数据 model
 * author: Totcy
 * date: 2017/11/4 21:45
 * update: 2017/11/4
 */

public class ImageListModel extends BaseModelImpl implements ImageListContract.Model {


    private ACache aCache;
    private Gson gson = new Gson();

    public ImageListModel(Context context) {
        super(context);
        aCache = ACache.get(context);
    }

    /**
     * 从网络获取数据
     *
     * @param type     类型
     * @param curPage  当前页
     * @param callback 回调presenter数据
     */
    @Override
    public void getImageListData(final String type, int typePosition, final int curPage, final DataCallback callback) {
        //拼接分页,typePosition == -1,第一页
        String path = type;
        if (curPage != PAGE_START) {
            path = path + "list_" + typePosition + "_" + curPage + ".html";
        }
        //rx2 写法
        final String finalPath = path;

        Disposable subscribe = Observable.create(new ObservableOnSubscribe<List<ImagesBean>>() {
            /**
             * Called for each Observer that subscribes.
             *
             * @param observableEmitter the safe emitter instance, never null
             * @throws Exception on error
             */
            @Override
            public void subscribe(ObservableEmitter<List<ImagesBean>> observableEmitter) throws Exception {
                List<ImagesBean> imageListDomainList = new ArrayList<>();
                try {
                    Document document = Jsoup.connect(CommonValues.BASE_URL_GIRLS + finalPath).get();
                    Element imageListelement = document.getElementById("content");
                    //Elements articles = imageListelement.getElementsByTag("article");
                    Elements imgElements = imageListelement.getElementsByClass("post-content post-text");
                    for (Element imageElement : imgElements) {

                        Element link = imageElement.select("a[href]").first();
                        String linkUrl = link.attr("abs:href");

                        Element image = imageElement.select("img").first();
                        if (image == null) {
                            continue;
                        }

                        String imageUrl = image.attr("abs:data-img");
                        String title = image.attr("alt");

                        //构建一个图片实体
                        ImagesBean bean = new ImagesBean();
                        bean.setUrl(imageUrl);
                        bean.setImageLink(linkUrl);
                        bean.setDescription(title);
                        imageListDomainList.add(bean);

                        if (CommonValues.isRunningTest)
                            Log.d("Tag", "linkUrl =" + linkUrl +" src =" + imageUrl + " title = " + title);
                    }
                    observableEmitter.onNext(imageListDomainList);
                    observableEmitter.onComplete();

                } catch (IOException exception) {
                    observableEmitter.onError(exception);
                }
            }
        })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<List<ImagesBean>>() {
                               @Override
                               public void accept(@NonNull List<ImagesBean> girlBeen) throws Exception {
                                   callback.onDataSuccess(girlBeen);
                                   if (curPage == PAGE_START) {
                                       aCache.put(CommonValues.BASE_URL_GIRLS + finalPath, gson.toJson(girlBeen));
                                   }
                               }
                           }, new Consumer<Throwable>() {
                               @Override
                               public void accept(@NonNull Throwable throwable) throws Exception {
                                   if (!NetUtil.isConnected(mContext) && curPage == PAGE_START) {
                                       String json = aCache.getAsString(CommonValues.BASE_URL_GIRLS + finalPath);
                                       if (!TextUtils.isEmpty(json)) {
                                           List<ImagesBean> images = gson.fromJson(
                                                   json,
                                                   new TypeToken<List<ImagesBean>>() {
                                                   }.getType()
                                           );
                                           callback.onDataSuccess(images);
                                       }
                                   }

                                   callback.onDataNotAvailable();
                                   if (CommonValues.isRunningTest)
                                       Log.e("ImageListModel", "onError: " + throwable.getMessage());
                               }
                           }
                );
    }

    @Override
    public void canCelRequest() {
    }

}